package com.gengzp.mq.server.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;
import java.sql.SQLException;

/**
 * @ClassName GengzpMqDataSource
 * @Description
 * @Author gengzp
 * @Date 2025/6/8 17:09
 */
@Configuration
@MapperScan(basePackages = "com.gengzp.mq.server.mapper", sqlSessionFactoryRef = "mqSqlSessionFactory")
public class GengzpMqDataSource {

    @Value("${spring.datasource.url}")
    private String url;

    @Value("${spring.datasource.username}")
    private String username;

    @Value("${spring.datasource.password}")
    private String password;

    /**
     * 配置 MQ 模块使用的独立数据源
     */
    @Bean
    public DataSource mqDataSource() throws SQLException {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");

        // 连接池配置
        dataSource.setInitialSize(5);
        dataSource.setMinIdle(5);
        dataSource.setMaxActive(20);
        dataSource.setMaxWait(60000);
        dataSource.setValidationQuery("SELECT 1");
        dataSource.setTestWhileIdle(true);
        dataSource.setTestOnBorrow(false);
        dataSource.setTestOnReturn(false);

        // 配置监控统计功能
        dataSource.setFilters("stat,wall,slf4j"); // 可选：log4j/logback 绑定

        return dataSource;
    }

    /**
     * 创建 SqlSessionFactory Bean
     */
    @Bean
    public SqlSessionFactory mqSqlSessionFactory(DataSource mqDataSource) throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(mqDataSource);
        factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources("classpath:mapper/*.xml"));
        return factoryBean.getObject();
    }

    /**
     * 配置事务管理器
     */
    @Bean
    public DataSourceTransactionManager mqTransactionManager(DataSource mqDataSource) {
        return new DataSourceTransactionManager(mqDataSource);
    }

}
